<?php
namespace Common\Controller;
use Think\Controller;

/**
 * 全局通用模块
 */
class CommonController extends Controller {
	protected $_moduleid;
	protected $_token;//当前登录用户的token
	protected $_mycache;//api数据redis句柄
	protected $_talkcache = array();//talk数据redis句柄
	protected $_custInfo;//当前登录用户的信息
	
	protected $_cust;//用户模型句柄
	protected $_cust_ext;//用户扩展信息模型句柄
	protected $_cust_location;//地理位置模型句柄
	protected $_cust_blacklist;//用户的黑名单模型句柄
	protected $_cust_permission;
	protected $_permission;
	protected $_verifycode;//短信模型句柄
	protected $_friend;//好友模型句柄
	protected $_chat;//聊天群组模型句柄
	protected $_chat_cust;//聊天群组成员模型句柄
	protected $_upload_file;//上传文件模型句柄
	protected $_notice;//通知模型句柄
	protected $_favorite;//收藏模型句柄
	protected $_face_favorite;//表情收藏
	
	protected $_ent;
	protected $_ent_cust;
	protected $_ent_depart;
	
	protected function _initialize(){
		$this->msg = L('STATUS_0');
		
		import("Common.Util.cachekey","",".php");
		import("Common.Util.pinyin","",".php");
		import("Common.Util.validate","",".php");
		import("Common.Util.tools","",".php");
		import("Common.Util.im","",".php");
		import("Common.Util.phpqrcode.phpqrcode","",".php");
		import("Common.Util.geohash","",".php");
		import("Common.Util.sms","",".php");
		import("Common.Util.aes","",".php");
		import("Common.Util.ucr","",".php");
		import("Common.Util.jwt","",".php");
	}
	
	public function indexAction(){
		echo "Can't access!";
	}
	
	//身份校验
	protected function _authVerify(){
		$headers = \tools::getRequestHeaders();
		$_custid = (int)$headers['_custid'];
		$_token = $headers['_token'];
		 
		$_custid = empty($_custid)?(int)I('request._custid'):$_custid;
		$_token = empty($_token)?I('request._token'):$_token;
		
		$_custid = empty($_custid)?(int)session('custid'):$_custid;
		$_token = empty($_token)?session('token'):$_token; 
		 
		if(empty($_token) || empty($_custid)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
		}
		
		//$_token = str_ireplace(" " , "+" , $_token);
		$_token_json = \aes::decrypt($_token, C('TOKEN_SALT'));
		$_token_arr = json_decode($_token_json , true);
		$current_custid = $_token_arr['custid'];
		$expire_time = $_token_arr['expire'];
		
		if($current_custid && $current_custid == $_custid && $expire_time > time()){
			$this->_token = $_token;
			$this->_custInfo = $this->_getCustInfo($_custid);
			
			@cookie('_custid' , $this->_custInfo['custid'] , array());
			
			return true;
		}else{
			return false;
		}
	}
	

	//身份认证
    protected function _auth(){
    	if(!$this->_authVerify()){
    		$this->status = 1002;
    		$this->msg = L('STATUS_1002');
    		$this->outPut();
    	}
    }
    
    
    protected function _makeIdeNum(){
    	$ideNumKey = \cachekey::$key['BASE_KEY_CONF']['IDE_NUM'];
    	 
    	if(empty($this->_cust)){
    		$this->_cust = new \Common\Model\CustModel();
    	}
    	
    	$result = $this->_cust->getMaxIdeNum();
    	if(!empty($result)){
    		$maxidenum = (int)$result['idenum'];
    	}else{
    		$maxidenum = 0;
    	}
    	 
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	if(empty($maxidenum))$maxidenum = 100000;
    	for($idenum=$maxidenum+1;$idenum<=$maxidenum+50000;$idenum++){
    		$this->_mycache->sadd($ideNumKey,$idenum);
    	}
    }
    
    protected function _getIdeNum(){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$ideNumKey = \cachekey::$key['BASE_KEY_CONF']['IDE_NUM'];
    	$idenum = $this->_mycache->spop($ideNumKey);
    	if(empty($idenum)){
    		$this->_makeIdeNum();
    		$idenum = $this->_mycache->spop($ideNumKey);
    	}
    	 
    	return $idenum;
    }
    
    
    //判断验证码是否正确
    protected function _checkVerCode($username , $vercode , $regtype=1){
    	if(empty($username) || empty($vercode) || !in_array($regtype , array(1,2,3))){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	 
    	if($regtype == 1)
    		$verKey = \cachekey::$key['BASE_KEY_CONF']['VERIFY_SMS_CODE'].$username;
    	elseif($regtype == 2)
    		$verKey = \cachekey::$key['BASE_KEY_CONF']['VERIFY_MAIL_CODE'].$username;
    	else 
    		$verKey = \cachekey::$key['BASE_KEY_CONF']['VERIFY_IMG_CODE'].$username;
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$tmpcode = $this->_mycache->get($verKey);//缓存中取验证码
    	if($tmpcode != $vercode){
    		$this->status = 1109;
    		$this->msg = L('STATUS_1109');
    		$this->outPut();
    	}
    }
    
    
    //删除验证码缓存
    protected function _delVerCode($username , $regtype=1){
    	if(empty($username) || !in_array($regtype , array(1,2,3))){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    
    	if($regtype == 1)
    		$verKey = \cachekey::$key['BASE_KEY_CONF']['VERIFY_SMS_CODE'].$username;
    	elseif($regtype == 2)
    		$verKey = \cachekey::$key['BASE_KEY_CONF']['VERIFY_MAIL_CODE'].$username;
    	else
    		$verKey = \cachekey::$key['BASE_KEY_CONF']['VERIFY_IMG_CODE'].$username;
    	
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$this->_mycache->del($verKey);//删除缓存中验证码
    }
    
    
    //获取签名
    protected function _getSign($username , $time){
    	$sign = \tools::getSign($username . "_" . $time);//个性签名
    	return $sign;
    }
    
    //检查签名
    protected function _checkSign($username,$time,$sign){
    	if(empty($username) || empty($time) || empty($sign)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	if(abs(time() - $time) > C('DEFAULT_SYSTEM_TIME_DIFFERENCE')){
    		$this->status = 1003;
    		$this->msg = L('STATUS_1003');
    		$this->outPut();
    	}
    	 
    	$tmpSign = \tools::getSign($username . "_" . $time);
    	if($tmpSign != $sign){//签名验证
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}
    }

    protected function _checkUserExistAndReturnWith($username,$mobile,$email){
        if (!empty($username)) {
            $custInfo =  $this->_cust->getCustInfoByOnlyUsername($username);

            return $custInfo;
        }
        if (!empty($mobile)) {
            $custInfo =  $this->_cust->getCustInfoByMobile($mobile);

            return $custInfo;
        }
        if (!empty($email)) {
            $custInfo =  $this->_cust->getCustInfoByEmail($email);
            return $custInfo;
        }
        return nil;
    }

    protected function _checkUserExistWith($username,$mobile,$email){
        if (!empty($username)) {
            $custInfo =  $this->_cust->getCustInfoByOnlyUsername($username);
            if(!empty($custInfo) && $custInfo['custid'] != $this->_custInfo['custid']){
                $this->status = 1112;
                $this->msg = L('STATUS_1112');
                $this->outPut();
            }
        }
        if (!empty($mobile)) {
            $custInfo =  $this->_cust->getCustInfoByMobile($mobile);
            if(!empty($custInfo) && $custInfo['custid'] != $this->_custInfo['custid']){
                $this->status = 1112;
                $this->msg = L('STATUS_1112');
                $this->outPut();
            }
        }
        if (!empty($email)) {
            $custInfo =  $this->_cust->getCustInfoByEmail($email);
            if(!empty($custInfo) && $custInfo['custid'] != $this->_custInfo['custid']){
                $this->status = 1112;
                $this->msg = L('STATUS_1112');
                $this->outPut();
            }
        }
    }
    
    //检查用户是否存在
    protected function _checkUserExist($username,$time,$sign){
    	if(empty($username) || empty($time) || empty($sign)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	$this->_checkSign($username,$time,$sign);
    	if(empty($this->_cust)) $this->_cust = new \Common\Model\CustModel();

        $custInfo =  $this->_cust->getCustInfoByUserName($username);

//    	if($regtype == 1){
//    		if(!\validate::isMobilePhoneNumber($username)){
//    			$this->status = 1118;
//    			$this->msg = L('STATUS_1118');
//    			$this->outPut();
//    		}
//    		$custInfo = $this->_cust->getCustInfoByMobile($username);
//    	}else{
//    		if(!\validate::isEmail($username)){
//    			$this->status = 1117;
//    			$this->msg = L('STATUS_1117');
//    			$this->outPut();
//    		}
//    		$custInfo = $this->_cust->getCustInfoByEmail($username);
//    	}
    	if(!empty($custInfo) && $custInfo['custid'] != $this->_custInfo['custid']){
    		$this->status = 1112;
    		$this->msg = L('STATUS_1112');
    		$this->outPut();
    	}
    }
    
    
    
    protected function _checkInEnt($entid){
    	if(empty($this->_ent)) $this->_ent = new \Common\Model\EntModel();
    	$resultData = $this->_ent->getAllEntByCust($this->_custInfo['custid']);
    	if(empty($resultData)){
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}else{
    		$inIt = false;
    		foreach($resultData as $ent){
    			if($ent['entid'] == $entid){
    				$inIt = true;
    				break;
    			}
    		}
    			
    		if($inIt == false){
    			$this->status = 1001;
    			$this->msg = L('STATUS_1001');
    			$this->outPut();
    		}
    	}
    	
    	return true;
    }
    
    
    protected function _checkEnt($entid){
    	if(empty($entid)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    
    	if(empty($this->_ent)) $this->_ent = new \Common\Model\EntModel();
    	$entInfo = $this->_ent->getEntById($entid);
    	if(empty($entInfo)){
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}
    
    	if($entInfo['custid'] != $this->_custInfo['custid'] && $entInfo['mcustid'] != $this->_custInfo['custid']){
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}
    
    	return $entInfo;
    }
    
    
    protected function _checkDepart($departid){
    	if(empty($departid)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    
    	if(empty($this->_ent_depart)) $this->_ent_depart = new \Common\Model\EntDepartmentModel();
    	$departInfo = $this->_ent_depart->getDepartById($departid);
    	if(empty($departInfo)){
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}
    
    	if($departInfo['custid'] != $this->_custInfo['custid'] && $departInfo['mcustid'] != $this->_custInfo['custid']){
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}
    
    	return $departInfo;
    }
    
    
    
    protected function _getCustInfo($custid , $querydb = 0){
    	$custInfo = $this->_getCustInfoCache($custid);
    	if(empty($custInfo) || $querydb == 1){
    		if(empty($this->_cust)) $this->_cust = new \Common\Model\CustModel();
    		$custInfo = $this->_cust->getCustInfoById($custid);
    		
    		if(empty($this->_cust_ext)) $this->_cust_ext = new \Common\Model\CustExtModel();
    		$custExtInfo = $this->_cust_ext->getCustExtInfoById($custid);
    		if(empty($custExtInfo['msgsetting'])){
    			$custExtInfo['msgsetting'] = '{"shock":"0","beep":"0","push":"0"}';
    		}
    		
    		$custInfo = array_merge($custInfo , $custExtInfo);
    		
    		$this->_setCustInfoCache($custInfo);
    	}
    	
    	if(!empty($custInfo['msgsetting']))$custInfo['msgsetting'] = json_decode($custInfo['msgsetting'] , true);
    	if(!empty($custInfo['dynamicsetting']))$custInfo['dynamicsetting'] = json_decode($custInfo['dynamicsetting'] , true);
    	
    	
    	unset($custInfo['password']);
    	return $custInfo;
    }
    
    
    //设置用户信息缓存
    protected function _setCustInfoCache($custInfo){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	
    	unset($arr['password']);
    	
    	$custKey = \cachekey::$key['BASE_KEY_CONF']['CUST_INFO'].$custInfo['custid'];
    	$this->_mycache->hmset($custKey , $custInfo);//缓存用户信息
    	 
    	if(!empty($custInfo['mobile']) && !empty($custInfo['custid'])){
    		$mobileKey = \cachekey::$key['BASE_KEY_CONF']['CUST_MOBILE'].$custInfo['mobile'];
    		$this->_mycache->set($mobileKey , $custInfo['custid']);
    	}
    }
    
    //取用户信息缓存
    protected function _getCustInfoCache($custid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	
    	$custKey = \cachekey::$key['BASE_KEY_CONF']['CUST_INFO'].$custid;
    	$ret = $this->_mycache->hgetall($custKey);//取用户缓存信息
    	return $ret;
    }
    
    
    protected function _getUploadError($errorNo){
    	switch ($errorNo) {
    		case '1'://The uploaded file exceeds the upload_max_filesize directive in php.ini
    			$size = ini_get("upload_max_filesize") / 1024;
    			$this->status = 1005;
    			$this->msg = L('STATUS_1005',array('size' => $size));
    			$this->outPut();
    			break;
    		case '2'://The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
    			$size = $_REQUEST['MAX_FILE_SIZE'] / 1024;
    			$this->status = 1005;
    			$this->msg = L('STATUS_1005',array('size' => $size));
    			$this->outPut();
    			break;
    		case '4'://No file was uploaded.
    			$this->status = 1006;
    			$this->msg = L('STATUS_1006');
    			$this->outPut();
    			break;
    		case '3'://The uploaded file was only partially uploaded
    		case '6'://Missing a temporary folder
    		case '7'://Failed to write file to disk
    		case '8'://File upload stopped by extension
    		case '999':
    		default:
    			$this->status = 1007;
    			$this->msg = L('STATUS_1007');
    			$this->outPut();
    	}
    }
    
    
    

    
    
    //获取文件
    protected function _getFile($fileid , $filehash , $w=0 , $h=0){
        if(empty($fileid) || empty($filehash)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	if(empty($this->_upload_file)){
    		$this->_upload_file = new \Common\Model\UploadFileModel();
    	}
    	$fileInfo = $this->_upload_file->getFileById($fileid);
    	if($fileInfo['filehash'] != $filehash){
    		$this->status = 1001;
    		$this->msg = L('STATUS_1001');
    		$this->outPut();
    	}
    	
    	if(!empty($fileInfo['file']) && file_exists($fileInfo['file'])){
    		if($w || $h){
    			$this->_viewImg($fileInfo['file'] , $w , $h);
    		}else{
	    		//header("Content-type: {$fileInfo['mimetype']}");
	    		//echo @readfile($fileInfo['file']);
    			/* $finfo = finfo_open(FILEINFO_MIME);
    			$mimetype = finfo_file($finfo, $fileInfo['file']);
    			finfo_close($finfo); */
    			
	    		$filecontent = file_get_contents($fileInfo['file']);
	    		header('Content-type: ' . $fileInfo['mimetype']);
	    		header('Content-length: ' . strlen($filecontent));
	    		echo $filecontent;
	    		die(0);
    		}
    	}
    }
    
    
    //查看图片
    protected function _viewImg($imgFile , $w=0 , $h=0){
    	$imgInfo = pathinfo($imgFile);
    	//if(empty($imgInfo['extension'])) $imgInfo['extension'] = "jpg";
    	
    	$imageAttr = getimagesize($imgFile);
    	$imgInfo['extension'] = $imageAttr[2];
    	if(empty($imgInfo['extension'])) $imgInfo['extension'] = "jpg";
    	
    	if((int)$imageAttr[0] > (int)$imageAttr[1]){
    		$h = 0;
    	}
    	
    	if((int)$imageAttr[0] < (int)$imageAttr[1]){
    		$w = 0;
    	}
    	
    	if(empty($w) && !empty($h)){
    		$w = ceil($imageAttr[0] * $h / $imageAttr[1]);
    	}
    	
    	if(!empty($w) && empty($h)){
    		$h = ceil($imageAttr[1] * $w / $imageAttr[0]);
    	}
    	
    	if($imgInfo['extension'] == "gif"){
    		$mimeType = "image/gif";
    	}elseif($imgInfo['extension'] == "png"){
    		$mimeType = "image/png";
    	}else{
    		$mimeType = "image/jpeg";
    	}
    	
    	if(empty($w) || empty($h)){
	    	header("Content-type: {$mimeType}");
	    	echo @readfile($imgFile);
	    	exit;
    	}
    	
    	$thumb = "{$imgInfo['dirname']}/{$imgInfo['filename']}.{$w}x{$h}.{$imgInfo['extension']}";
    	if(!file_exists($thumb)){
    		$image = new \Think\Image();
    		$image->open($imgFile);
    		$image->thumb($w, $h,\Think\Image::IMAGE_THUMB_SCALE)->save($thumb);// 生成一个缩放后填充为{$w}x{$h}的缩略图并保存为{$w}x{$h}.jpg
    	}
    	
    	header("Content-type: {$mimeType}");
    	echo @readfile($thumb);
    	exit;
    }
    
    //取头像
    protected function _avatar($id , $type , $w , $h){
    	if(empty($id) || empty($type)){// || empty($w) || empty($h)
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	$avatar_exist = false;
    	if($type == 1) $res = \tools::makeAvatarFilePath(C('CUST_AVATAR_PATH') , $id);
    	if($type == 2) $res = \tools::makeAvatarFilePath(C('CHAT_AVATAR_PATH') , $id);
    	
    	$targetpath = $res['targetpath'];
    	$avatars[] =  "{$targetpath}{$id}.jpg";
    	$avatars[] =  "{$targetpath}{$id}.png";
    	$avatars[] =  "{$targetpath}{$id}.gif";
    	$avatar = "";
    	foreach($avatars as $avatar){
    		if(file_exists($avatar)){
    			$avatar_exist = true;
    			break;
    		}
    	}
    	
    	if($avatar_exist){
    		$this->_viewImg($avatar , $w , $h);
    	}else{
    		if($type == 1){//用户头像
    			//默认头像
    			$this->_viewImg(C('DEFAULT_AVATAR') , $w , $h);
    		}
    		
    		if($type == 2){//群头像
    			if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    			
    			$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_CUST'].$id;
    			$custList = $this->_mycache->get($listKey);//取聊天群成员缓存信息
    			if(empty($custList)){
    				if(empty($this->_chat_cust)) $this->_chat_cust = new \Common\Model\ChatCustModel();
    				$custList = $this->_chat_cust->getCustInfoByChatId($id,1);
    			}
    			
    			if(empty($custList)){
    				//默认头像
    				$this->_viewImg(C('DEFAULT_AVATAR') , $w , $h);
    			}
    			
    			$pic_list = array();
				foreach($custList as &$cust){
					$res = \tools::makeAvatarFilePath(C('CUST_AVATAR_PATH') , $cust['custid']);
					$filetarget = $res['filetarget'];
					if(file_exists($filetarget)){
						$pic_list[] = $filetarget;
					}
					
					$custs[] = $cust['custid'];
				}
				
				if(empty($pic_list)){
					//默认头像
					$this->_viewImg(C('DEFAULT_AVATAR') , $w , $h);
				}
				
				$res = \tools::makeAvatarFilePath(C('CHAT_AVATAR_PATH') , $id);
				$targetpath = $res['targetpath'];
				$pic_list_cnt = count($pic_list);
				if($pic_list_cnt > 9) $pic_list_cnt = 9;//最多取9张个人头像拼装
				$filetarget = "{$targetpath}{$id}_{$pic_list_cnt}.jpg";
				if(file_exists($filetarget)){
					$this->_viewImg($filetarget , $w , $h);
				}else{
					\tools::makeChatAvatar($pic_list , $filetarget);
					
					//系统消息
					$msg['chat_id'] = $id;
					$msg['type'] = 26;
					$msg['content'] = "";
					\im::sendMsg(3, $custs, array(), $msg);
					
					$this->_viewImg($filetarget , $w , $h);
				}
    		}
    	}
    	
    }
    
    
    
    
    
    
    
    
    
    //发送文件
    protected function _sendFile($apiReturn = true){
    	$filename = $_FILES['uploadedFile']['name'];
    	$errorNo = $_FILES['uploadedFile']['error'];
    	if($errorNo && $apiReturn){
    		$this->_getUploadError($errorNo);
    	}
    		
    	if(empty($filename)){
    		if($apiReturn){
    			$this->status = 1010;
    			$this->msg = L('STATUS_1010');
    			$this->outPut();
    		}else{
    			return null;
    		}
    	}
    		
    	$filetarget = C('UPLOAD_FILE_PATH').$filename;
    	$res = \tools::makeFilePath(C('UPLOAD_FILE_PATH') , $filename);
    	$filetarget = $res['filetarget'];
    	$targetpath = $res['targetpath'];
    
    	$ret = move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $filetarget);
    	if($ret){
    		$data['custid'] = $this->_custInfo['custid'];
    		$data['file'] = $filetarget;
    		$data['filesize'] = $_FILES['uploadedFile']['size'];
    		$data['filehash'] = md5($filetarget);
    		$data['mimetype'] = strtolower($_FILES['uploadedFile']['type']);
    		if(empty($this->_upload_file)){
    			$this->_upload_file = new \Common\Model\UploadFileModel();
    		}
    		$fileid = $this->_upload_file->addFile($data);
    
    		$returnData['fileid'] = $fileid;
    		$returnData['filesize'] = $data['filesize'];
    		$returnData['filename'] = $filename;
    		$returnData['filehash'] = $data['filehash'];
    		$returnData['width'] = "0";
    		$returnData['height'] = "0";
    		if($data['mimetype'] == "image/gif" || $data['mimetype'] == "image/jpeg" || $data['mimetype'] == "image/png"){
    			$imageAttr   =   getimagesize($filetarget);
    			$returnData['width'] = $imageAttr[0];
    			$returnData['height'] = $imageAttr[1];
    		}
    
    		if($apiReturn){
    			$this->data = $returnData;
    			$this->outPut();
    		}else{
    			return $returnData;
    		}
    	}else{
    		if($apiReturn){
    			$this->status = 1010;
    			$this->msg = L('STATUS_1010');
    			$this->outPut();
    		}else{
    			return null;
    		}
    	}
    }
    
    
    //发送文件
    protected function _sendFile2($apiReturn = true){
    	if(!empty($_FILES['file'])){
    		$filename = $_FILES['file']['name'];
    		$errorNo = $_FILES['file']['error'];
    		if($errorNo && $apiReturn){
    			$this->_getUploadError($errorNo);
    		}
    		
	    	$filetarget = C('UPLOAD_FILE_PATH').$filename;
	    	$res = \tools::makeFilePath(C('UPLOAD_FILE_PATH') , $filename);
	    	$filetarget = $res['filetarget'];
	    	$targetpath = $res['targetpath'];
	    
	    	$ret = move_uploaded_file($_FILES['file']['tmp_name'], $filetarget);
	    	if($ret){
	    		$data['custid'] = $this->_custInfo['custid'];
	    		$data['file'] = $filetarget;
	    		$data['filesize'] = $_FILES['file']['size'];
	    		$data['filehash'] = md5($filetarget);
	    		$data['mimetype'] = strtolower($_FILES['file']['type']);
	    		if(empty($this->_upload_file)){
	    			$this->_upload_file = new \Common\Model\UploadFileModel();
	    		}
	    		$fileid = $this->_upload_file->addFile($data);
	    
	    		$returnData['fileid'] = $fileid;
	    		$returnData['filesize'] = $data['filesize'];
	    		$returnData['filename'] = $filename;
	    		$returnData['filehash'] = $data['filehash'];
	    		$returnData['width'] = "0";
	    		$returnData['height'] = "0";
	    		if($data['mimetype'] == "image/gif" || $data['mimetype'] == "image/jpeg" || $data['mimetype'] == "image/png"){
	    			$imageAttr   =   getimagesize($filetarget);
	    			$returnData['width'] = $imageAttr[0];
	    			$returnData['height'] = $imageAttr[1];
	    		}
	    
	    		if($apiReturn){
	    			$this->data = $returnData;
	    			$this->outPut();
	    		}else{
	    			return $returnData;
	    		}
	    	}else{
	    		if($apiReturn){
	    			$this->status = 1010;
	    			$this->msg = L('STATUS_1010');
	    			$this->outPut();
	    		}else{
	    			return null;
	    		}
	    	}
    	}else{
    		$filename = $_REQUEST["name"];
    		$filetarget = C('UPLOAD_FILE_PATH').$filename;
    		$res = \tools::makeFilePath(C('UPLOAD_FILE_PATH') , $filename);
    		$filetarget = $res['filetarget'];
    		$targetpath = $res['targetpath'];
    		
			if(!$out = @fopen($filetarget, "wb")) {
				if($apiReturn){
	    			$this->status = 1010;
	    			$this->msg = L('STATUS_1010');
	    			$this->outPut();
	    		}else{
	    			return null;
	    		}
			}
    		
			if(!$in = @fopen("php://input", "rb")){
				if($apiReturn){
	    			$this->status = 1010;
	    			$this->msg = L('STATUS_1010');
	    			$this->outPut();
	    		}else{
	    			return null;
	    		}
			}
			
			while ($buff = fread($in, 4096)) {
				fwrite($out, $buff);
			}
			
			@fclose($out);
			@fclose($in);
			
			$data['custid'] = $this->_custInfo['custid'];
			$data['file'] = $filetarget;
			$data['filesize'] = filesize($filetarget);
			$data['filehash'] = md5($filetarget);
			$data['mimetype'] = \tools::get_mimetype($filename);
			if(empty($this->_upload_file)){
				$this->_upload_file = new \Common\Model\UploadFileModel();
			}
			$fileid = $this->_upload_file->addFile($data);
			 
			$returnData['fileid'] = $fileid;
			$returnData['filesize'] = $data['filesize'];
			$returnData['filename'] = $filename;
			$returnData['filehash'] = $data['filehash'];
			$returnData['width'] = "0";
			$returnData['height'] = "0";
			if($data['mimetype'] == "image/gif" || $data['mimetype'] == "image/jpeg" || $data['mimetype'] == "image/png"){
				$imageAttr   =   getimagesize($filetarget);
				$returnData['width'] = $imageAttr[0];
				$returnData['height'] = $imageAttr[1];
			}
			 
			if($apiReturn){
				$this->data = $returnData;
				$this->outPut();
			}else{
				return $returnData;
			}
    	}
    }
    
    
    
    //设置地理位置
    protected function _setLocation($latitude, $longitude , $hash , $custid=0){
    	if(empty($this->_cust_location)) $this->_cust_location = new \Common\Model\CustLocationModel();
    		
    	$data = array();
    	$data['longitude'] = $longitude;
    	$data['latitude'] = $latitude;
    	$data['custid'] = empty($custid) ? $this->_custInfo['custid'] : $custid;
    	$data['geohash'] = $hash;
    		
    	$ret = $this->_cust_location->addLocation($data);
    	if(!$ret){
    		$this->status = 1008;
    		$this->msg = L('STATUS_1008');
    		$this->outPut();
    	}
    }
    
    //删除地理位置
    protected function _delLocation($custid){
    	if(empty($this->_cust_location)) $this->_cust_location = new \Common\Model\CustLocationModel();
    	$this->_cust_location->deleteLocation($custid);
    	$this->outPut();
    }
    
    
    //通知列表
    protected function _getNotices($data){
    	if(empty($this->_notice)) $this->_notice = new \Common\Model\NoticeModel();
    	$ret = $this->_notice->getNoticeList($data);
    	return $ret;
    }
    
    //通知详情
    protected function _getNotice($data){
    	if(empty($this->_notice)) $this->_notice = new \Common\Model\NoticeModel();
    	$ret = $this->_notice->getNotice($data);
    	return $ret;
    }
    
    //创建通知
    protected function _createNotice($data){
    	if(empty($this->_notice)) $this->_notice = new \Common\Model\NoticeModel();
    	$ret = $this->_notice->addNotice($data);
    	return $ret;
    }
    
    //处理通知
    protected function _updateNotice($data){
    	if(empty($this->_notice)) $this->_notice = new \Common\Model\NoticeModel();
    	$ret = $this->_notice->updateNotice($data);
    	return $ret;
    }
    
    //删除通知
    protected function _delNotice($data){
    	if(empty($this->_notice)) $this->_notice = new \Common\Model\NoticeModel();
    	$ret = $this->_notice->deleteNotice($data);
    	return $ret;
    }
    
    
    //取好友列表信息
    protected function _getFriendList($custid){
    	$friendList = $this->_getFriendListCache($custid);
    	if(empty($friendList)){
    		$data['custid'] = $custid;
    		if(empty($this->_friend)) $this->_friend = new \Common\Model\FriendModel();
    		$friendList = $this->_friend->getFriendList($data);
    		$friendList = $friendList['data'];
    		if(!empty($friendList)){
    			foreach($friendList as &$friend){
    				$custInfo = $this->_getCustInfo($friend['custid']);
    				
    				$friend['_nickname'] = $friend['nickname'];
    				$friend['nickname'] = $custInfo['nickname'];
    			}
    			
    			$this->_setFriendListCache($custid , $friendList);
    			foreach($friendList as &$friend){
    				if(!empty($friend['msgsetting']))
    					$friend['msgsetting'] = json_decode($friend['msgsetting'] , true);
    				else
    					$friend['msgsetting'] = array('push'=>'0');
    			}
    		}else{
    			$friendList = array();
    		}
    	}else{
    		foreach($friendList as &$friend){
    			$custInfo = $this->_getCustInfo($friend['custid']);
    			
    			$friend['_nickname'] = $friend['nickname'];
    			$friend['nickname'] = $custInfo['nickname'];
    			
    			$friend['msgsetting'] = json_decode($friend['msgsetting'] , true);
    		}
    	}
    	 
    	return $friendList;
    }
    
    
    //缓存好友列表信息
    protected function _setFriendListCache($custid , $friendList){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CUST_FRIENDS'].$custid;
    	$this->_mycache->set($listKey , $friendList);
    	$this->_mycache->expire($listKey , C('FRIEND_LIST_EXPIRE'));
    }
    
    //取好友列表缓存信息
    protected function _getFriendListCache($custid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CUST_FRIENDS'].$custid;
    	$ret = $this->_mycache->get($listKey);
    	return $ret;
    }
    
    //删除缓存好友列表信息
    protected function _delFriendListCache($custid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CUST_FRIENDS'].$custid;
    	$this->_mycache->rm($listKey);
    }
    
    
    //设置某个用户所在的聊天群列表缓存
    protected function _setChatListCache($custid , $chatList){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_LIST'].$custid;
    	$this->_mycache->set($listKey , $chatList);//缓存聊天群列表信息
    	$this->_mycache->expire($listKey , C('CHAT_LIST_EXPIRE'));
    }
    
    //取得某个用户所在的聊天群列表缓存
    protected function _getChatListCache($custid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_LIST'].$custid;
    	$ret = $this->_mycache->get($listKey);//取聊天群列表缓存信息
    	return $ret;
    }
    
    //取得某个用户所在的聊天群列表
    protected function _getChatList($custid){
    	$chatList = $this->_getChatListCache($custid);
    	if(!empty($chatList)){
    		return $chatList;
    	}
    	
    	$chatList = array();
    	if(empty($this->_chat_cust)) $this->_chat_cust = new \Common\Model\ChatCustModel();
    	$chatids = $this->_chat_cust->getChatIdsByCustId($custid);
    	if(!empty($chatids)){
    		$chatIds = array();
    		foreach($chatids as &$chat){
    			array_push($chatIds , (int)$chat['chatid']);
    		}
    		
    		$data['chatIds'] = $chatIds;
    		if(empty($this->_chat)) $this->_chat = new \Common\Model\ChatModel();
    		$chatList = $this->_chat->getChatList($data);
    		if(!empty($chatList)){
	    		foreach($chatList['data'] as &$chat){
	    			unset($chat['custid']);
	    			unset($chat['introduce']);
	    			unset($chat['createtime']);
	    			unset($chat['updatetime']);
	    		}
	    		$chatList = $chatList['data'];
    		}else{
    			$chatList = array();
    		}
    		
    		$this->_setChatListCache($custid , $chatList);
    	}
    	
    	return $chatList;
    }
    
    
    //删除某个用户所在的聊天群列表缓存
    protected function _delChatListCache($custid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_LIST'].$custid;
    	$this->_mycache->rm($listKey);//删除聊天群列表信息
    }
    
    
    //设置某个聊天群的成员列表缓存
    protected function _setChatCustCache($chatid , $custList){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_CUST'].$chatid;
    	$this->_mycache->set($listKey , $custList);//缓存聊天群成员信息
    	$this->_mycache->expire($listKey , C('CHAT_CUST_EXPIRE'));
    }
    
    //取得某个聊天群的成员列表缓存
    protected function _getChatCustCache($chatid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_CUST'].$chatid;
    	$ret = $this->_mycache->get($listKey);//取聊天群成员缓存信息
    	return $ret;
    }
    
    protected function _getChatCust($chatid){
    	if(empty($chatid)) return array();
    	$custList = $this->_getChatCustCache($chatid);
    	if(!empty($custList)){
    		return $custList;
    	}
    	
		if(empty($this->_chat_cust)) $this->_chat_cust = new \Common\Model\ChatCustModel();
		$custList = $this->_chat_cust->getCustInfoByChatId($chatid,"1");
		if(!empty($custList)){
			foreach($custList as &$v){
				$custid = $v['custid'];
				$custInfo = $this->_getCustInfo($custid);
				$v['pinyinname'] = $custInfo['pinyinname'];
				$v['msgsetting'] = json_decode($v['msgsetting'] , true);
				if(empty($v['nickname'])) $v['nickname'] = $custInfo['nickname'];
			}
			$this->_setChatCustCache($chatid , $custList);
		}else{
			$custList = array();
		}
    	
    	return $custList;
    }
    
    protected function _getNicknameInChat($chatid , $custid){
    	$nickname = "";
    	$custs = $this->_getChatCust($chatid);
    	if(!empty($custs)){
    		foreach($custs as $cust){
    			if(!empty($custid) && $cust['custid'] == $custid){
    				$nickname = $cust['nickname'];
    				break;
    			}
    		}
    	}
    	
    	if(!empty($custid) && empty($nickname)){
    		$custInfo = $this->_getCustInfo($custid);
    		return $custInfo['nickname'];
    	}else{
    		return $nickname;
    	}
    }
    
    
    //删除某个聊天群的成员列表缓存
    protected function _delChatCustCache($chatid){
    	if(empty($this->_mycache)) $this->_mycache = S(C('REDIS_DSN'));
    	$listKey = \cachekey::$key['BASE_KEY_CONF']['CHAT_CUST'].$chatid;
    	$this->_mycache->rm($listKey);//删除聊天群成员信息
    }
    
    
    protected function _getAllMsgSetting($custid){
    	$returnData = array();
    	$idx = 0;
		if(empty($this->_chat_cust)) $this->_chat_cust = new \Common\Model\ChatCustModel();
		$result = $this->_chat_cust->getChatIdsByCustId($custid);
		if(!empty($result)){
			foreach($result as $chat){
				$returnData[$idx]['session_type'] = 2;
				$returnData[$idx]['session_id'] = (int)$chat['chatid'];
				$returnData[$idx]['msgsetting'] = json_decode($chat['msgsetting'] , true);
				$idx++;
			}
		}
		
		if(empty($this->_friend)) $this->_friend = new \Common\Model\FriendModel();
		$result = $this->_friend->getFriendIdsByCustId($custid);
		if(!empty($result)){
			foreach($result as $friend){
				$returnData[$idx]['session_type'] = 1;
				$returnData[$idx]['session_id'] = (int)$friend['tcustid'];
				$returnData[$idx]['msgsetting'] = json_decode($friend['msgsetting'] , true);
				$idx++;
			}
		}
		
		return $returnData;
    }
    
    //检查权限,用于管理后台
    protected function _checkPermission($custid , $permissionid){
    	//return true;
    	if(empty($this->_cust_permission)) $this->_cust_permission = new \Common\Model\CustPermissionModel();
    	$custInfo = $this->_getCustInfo($custid);
    	if($custInfo['issuper'] == "1") return true;
    		
    	$rets = $this->_cust_permission->getCustPermission($custid , $permissionid);
    	if(!empty($rets)){
    		return true;
    	}
    		
    	return false;
    }

    //记录错误日志
    protected function _logError($error_msg , $fileperfix = "push_error") {
    	$file = "./log/{$fileperfix}_" . date("Y-m-d") . ".log";
    	$str = "[ " . date("Y-m-d H:i:s", time()) . " ] :" . $error_msg . "\n";
    	error_log($str, 3, $file);
    }
}
